import Stomp from 'stompjs'
export const MQTT_SERVICE = 'ws://117.175.0.141:15674/ws' // mqtt服务地址
export const MQTT_USERNAME = 'yuing' // 连接用户名
export const MQTT_PASSWORD = 'yuyi2021' //  连接密码
export const Virtual_host = 'order' //  侦听器端口

var client

/**
 * 连接
 * @param {*} ConnectedCallBack
 * @param {*} onFailedCallBack
 * @returns
 */
export function connect(ConnectedCallBack, onFailedCallBack) {
  let headers = {
    login: MQTT_USERNAME,
    passcode: MQTT_PASSWORD,
    host: Virtual_host
  }
  let ws = new WebSocket(MQTT_SERVICE)
  client = Stomp.over(ws)
  client.heartbeat.outgoing = 0
  client.heartbeat.incoming = 0
  client.connect(headers, ConnectedCallBack, onFailedCallBack)
}

/**
 * 订阅
 * @param {*} topic
 */
export function subscribe(topic, responseCallback) {
  client.subscribe(topic, responseCallback)
}

/**
 * 断开连接
 */
export function close() {
  client.disconnect(function() {
    window.console.log('已断开连接')
  })
}

export default {
  connect,
  subscribe,
  close
}
